package com.ruoyi.project.system.interact.controller;

import java.util.List;
import java.io.IOException;
import java.util.Date;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.system.interact.domain.Oath;
import com.ruoyi.project.system.interact.service.IOathService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.config.ServerConfig;

/**
 * 入党宣誓Controller
 * 
 * @author ruoyi
 * @date 2023-07-15
 */
@Controller
@RequestMapping("/hui/interact/oath")
public class OathController extends BaseController
{
    private String prefix = "system/interact";

    @Autowired
    private IOathService oathService;

    @Autowired
    private ServerConfig serverConfig;

    /**
     * 跳转到入党宣誓页面
     */
    @RequiresPermissions("hui:interact:oath:view")
    @GetMapping()
    public String oath()
    {
        return prefix + "/oath";
    }

    /**
     * 查询入党宣誓列表
     */
    @RequiresPermissions("hui:interact:oath:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Oath oath)
    {
        startPage();
        List<Oath> list = oathService.selectOathList(oath);
        return getDataTable(list);
    }

    /**
     * 导出入党宣誓列表
     */
    @RequiresPermissions("hui:interact:oath:export")
    @Log(title = "入党宣誓", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Oath oath)
    {
        List<Oath> list = oathService.selectOathList(oath);
        ExcelUtil<Oath> util = new ExcelUtil<Oath>(Oath.class);
        return util.exportExcel(list, "入党宣誓数据");
    }

    /**
     * 新增入党宣誓
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存入党宣誓
     */
    @RequiresPermissions("hui:interact:oath:add")
    @Log(title = "入党宣誓", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Oath oath, MultipartFile file) throws IOException
    {
        if (file != null && !file.isEmpty())
        {
            String filePath = RuoYiConfig.getUploadPath() + "/videos/oath/";
            String fileName = FileUploadUtils.upload(filePath, file);
            
            oath.setFileName(file.getOriginalFilename());
            oath.setVideoUrl(fileName);
            oath.setFileSize(file.getSize());
        }
        
        oath.setCreateBy(getLoginName());
        oath.setCreateTime(new Date());
        oath.setDelFlag("0");
        
        return toAjax(oathService.insertOath(oath));
    }

    /**
     * 修改入党宣誓
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        Oath oath = oathService.selectOathById(id);
        mmap.put("oath", oath);
        return prefix + "/edit";
    }

    /**
     * 修改保存入党宣誓
     */
    @RequiresPermissions("hui:interact:oath:edit")
    @Log(title = "入党宣誓", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Oath oath, MultipartFile file) throws IOException
    {
        if (file != null && !file.isEmpty())
        {
            String filePath = RuoYiConfig.getUploadPath() + "/videos/oath/";
            String fileName = FileUploadUtils.upload(filePath, file);
            
            oath.setFileName(file.getOriginalFilename());
            oath.setVideoUrl(fileName);
            oath.setFileSize(file.getSize());
        }
        
        oath.setUpdateBy(getLoginName());
        oath.setUpdateTime(new Date());
        
        return toAjax(oathService.updateOath(oath));
    }

    /**
     * 删除入党宣誓
     */
    @RequiresPermissions("hui:interact:oath:remove")
    @Log(title = "入党宣誓", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(oathService.deleteOathByIds(ids));
    }

    /**
     * 上传视频文件
     */
    @RequiresPermissions("hui:interact:oath:add")
    @PostMapping("/uploadVideo")
    @ResponseBody
    public AjaxResult uploadVideo(MultipartFile file) throws IOException
    {
        try
        {
            if (file == null || file.isEmpty())
            {
                return error("请选择要上传的视频文件");
            }

            String filePath = RuoYiConfig.getUploadPath() + "/videos/oath/";
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", file.getOriginalFilename());
            ajax.put("videoUrl", fileName);
            ajax.put("fileSize", file.getSize());
            ajax.put("url", url);
            return ajax;
        }
        catch (Exception e)
        {
            return error(e.getMessage());
        }
    }

    /**
     * 获取视频下载路径（重定向到通用下载接口）
     */
    @RequiresPermissions("hui:interact:oath:view")
    @GetMapping("/download/{id}")
    public void download(@PathVariable("id") Long id, HttpServletResponse response) throws IOException
    {
        try
        {
            Oath oath = oathService.selectOathById(id);
            if (oath == null)
            {
                response.setContentType("text/html;charset=utf-8");
                response.getWriter().print("视频文件不存在");
                return;
            }

            // 重定向到通用资源下载接口
            String redirectUrl = "/common/download/resource?resource=" + oath.getVideoUrl();
            response.sendRedirect(redirectUrl);
        }
        catch (Exception e)
        {
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().print("视频下载失败：" + e.getMessage());
        }
    }

    /**
     * 获取视频播放地址
     */
    @RequiresPermissions("hui:interact:oath:view")
    @GetMapping("/getVideoUrl/{id}")
    @ResponseBody
    public AjaxResult getVideoUrl(@PathVariable("id") Long id)
    {
        Oath oath = oathService.selectOathById(id);
        if (oath == null)
        {
            return error("视频不存在");
        }
        
        String url = serverConfig.getUrl() + oath.getVideoUrl();
        return AjaxResult.success().put("url", url);
    }
}